// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package clusterutil

import (
	"os"

	"github.com/kumose/errors"
	"github.com/kumose/kmopt/pkg/environment"
	"github.com/kumose/kmopt/pkg/repository"
	"github.com/kumose/kmopt/pkg/repository/v1manifest"
	"github.com/kumose/kmopt/pkg/utils"
)

// Repository exports interface to kmopt-cluster
type Repository interface {
	DownloadComponent(comp, version, target string) error
	VerifyComponent(comp, version, target string) error
	ComponentBinEntry(comp, version string) (string, error)
}

type repositoryT struct {
	repo repository.Repository
}

// NewRepository returns repository
func NewRepository(os, arch string) (Repository, error) {
	repo := environment.GlobalEnv().V1Repository().WithOptions(repository.Options{
		GOOS:              os,
		GOARCH:            arch,
		DisableDecompress: true,
	})
	return &repositoryT{repo}, nil
}

func (r *repositoryT) DownloadComponent(comp, version, target string) error {
	versionItem, err := r.repo.ComponentVersion(comp, version, false)
	if err != nil {
		return err
	}

	return r.repo.DownloadComponent(versionItem, target)
}

func (r *repositoryT) VerifyComponent(comp, version, target string) error {
	versionItem, err := r.repo.ComponentVersion(comp, version, true)
	if err != nil {
		return err
	}

	file, err := os.Open(target)
	if err != nil {
		return err
	}
	defer file.Close()

	if err := utils.CheckSHA256(file, versionItem.Hashes[v1manifest.SHA256]); err != nil {
		return errors.Errorf("validation failed for %s: %s", target, err)
	}
	return nil
}

func (r *repositoryT) ComponentBinEntry(comp, version string) (string, error) {
	versionItem, err := r.repo.ComponentVersion(comp, version, true)
	if err != nil {
		return "", err
	}

	return versionItem.Entry, nil
}
